<script setup lang="ts">
  import { createVNode, ref, watch } from 'vue'
  import CreateCategory from './CreateCategory.vue'
  import EditCategory from './EditCategory.vue'
  import { message, Modal } from 'ant-design-vue'
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
  import { deleteMainlyCategoryReq } from '@/api'
  import { useSearchStore } from '@/store/search'
  import { storeToRefs } from 'pinia'
  import usePagination from '@/hooks/usePagination'

  const searchStore = useSearchStore()
  const { searchValue } = storeToRefs(searchStore)

  const props = defineProps([
    'categoryLevel1',
    'categoryLevel2',
    'refreshCategoryData',
  ])

  const categoryData1 = ref<any[]>([])
  const categoryData2 = ref<any[]>([])
  const initData = () => {
    categoryData1.value = JSON.parse(JSON.stringify(props.categoryLevel1))
    categoryData2.value = JSON.parse(JSON.stringify(props.categoryLevel2))
  }

  watch(
    [() => props.categoryLevel1, () => props.categoryLevel2],
    ([value1, value2]) => {
      if (value1 || value2) initData()
    },
    { immediate: true }
  )

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      width: '200px',
      key: 'name',
    },
    { title: '描述', dataIndex: 'description', width: '300px' },
    {
      title: '分类等级',
      dataIndex: 'level',
      width: '200px',
      customRender: ({ text }: any) => {
        return text === '0' ? '一级分类' : '二级分类'
      },
    },
    {
      title: '上级分类',
      dataIndex: 'parentId',
      width: '200px',
      customRender: ({ text }: any) => {
        if (!text) {
          return '无'
        } else {
          const parent = props.categoryLevel1.find(
            (item: any) => item.id === text
          )
          return parent ? parent.name : '未知分类'
        }
      },
    },
    {
      title: '置顶',
      dataIndex: 'isPoint',
      width: '200px',
      customRender: ({ text }: any) => {
        return text ? '是' : '否'
      },
    },
    { title: '操作', key: 'operation' },
  ]

  const level = ref('0')

  const levelChange = (value: string) => {
    level.value = value
  }

  const showCreate = ref(false)
  const showEdit = ref(false)
  const editRecord = ref(null)

  // 添加成功后更新数据
  watch(showCreate, (val, oldVal) => {
    if (oldVal && !val) {
      props.refreshCategoryData()
    }
  })

  watch(showEdit, (val, oldVal) => {
    if (oldVal && !val) {
      props.refreshCategoryData()
    }
  })

  const handleCreateOk = () => {
    showCreate.value = false
  }

  const handleEditOk = () => {
    showEdit.value = false
  }

  const editCategory = (record: any) => {
    editRecord.value = record
    showEdit.value = true
  }

  const deleteCategory = async (record: any) => {
    let hasChildren = false
    if (record.level === '0') {
      hasChildren = props.categoryLevel2.some(
        (item: any) => item.parentId === record.id
      )
    } else {
      // 判断二级分类下是否有子分类
    }
    if (hasChildren) {
      Modal.error({
        title: '删除失败',
        content: '该分类下有子分类，请先删除子分类。',
      })
      return
    }
    deleteConfirm(record)
  }

  const deleteConfirm = (record: any) => {
    Modal.confirm({
      title: `确认删除类别 "${record.name}" 吗？`,
      icon: createVNode(ExclamationCircleOutlined),
      content: '如果确认删除请点击确认按钮',
      async onOk() {
        try {
          const res = await deleteMainlyCategoryReq({ id: record.id })
          if (res?.data) {
            message.success('删除成功')
            props.refreshCategoryData()
          }
        } catch (error) {}
      },
      // eslint-disable-next-line @typescript-eslint/no-empty-function
      onCancel() {},
    })
  }

  watch(searchValue, () => {
    if (searchValue.value) {
      categoryData1.value = props.categoryLevel1?.filter((item: any) =>
        item.name.includes(searchValue.value)
      )
      categoryData2.value = props.categoryLevel2?.filter((item: any) =>
        item.name.includes(searchValue.value)
      )
    } else {
      initData()
    }
  })

  const { pagination } = usePagination()
</script>

<template>
  <a-row class="top-row">
    <a-select
      ref="select"
      v-model:value="level"
      style="width: 120px"
      @change="levelChange"
    >
      <a-select-option value="0">一级分类</a-select-option>
      <a-select-option value="1">二级分类</a-select-option>
    </a-select>
    <a-button
      class="headerButton"
      @click="showCreate = true"
      >添加分类</a-button
    >
  </a-row>
  <a-table
    :columns="columns"
    :data-source="level === '0' ? categoryData1 : categoryData2"
    :pagination="pagination"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'operation'">
        <a
          class="tableAction"
          @click="editCategory(record)"
          >编辑</a
        >
        <a
          class="tableAction"
          @click="deleteCategory(record)"
          >删除</a
        >
      </template>
      <template v-if="column.key === 'name'">
        <a class="tableAction">{{ record.name }}</a>
      </template>
    </template>
  </a-table>
  <a-modal
    v-model:open="showCreate"
    title="添加分类"
    @ok="handleCreateOk"
    width="600px"
    :footer="null"
    destroyOnClose
  >
    <CreateCategory
      v-model="showCreate"
      :columnData0="categoryLevel1"
    />
  </a-modal>
  <a-modal
    v-model:open="showEdit"
    title="编辑分类"
    @ok="handleEditOk"
    width="600px"
    :footer="null"
    destroyOnClose
  >
    <EditCategory
      v-model="showEdit"
      :record="editRecord"
      :categoryLevel1="categoryLevel1"
    />
  </a-modal>
</template>

<style scoped lang="less">
  .top-row {
    margin: 16px 0;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .headerButton {
      background-color: var(--color-blue);
      color: white;
      font-size: 12px;
    }
  }

  .tableAction {
    margin-right: 8px;
    cursor: pointer;
  }
</style>
